// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  // 给定 DYNAMIC_CURRENT_ENV 常量：接下来的 API 调用都将请求到与该云函数当前所在环境相同的环境
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 获取时间


// 云函数入口函数
exports.main = async (event, context) => {
  var _ = cloud.database().command;
  var DB1 = cloud.database().collection('coupon');
  var DB2 = cloud.database().collection('login_coupon');

  if (event.usetype == 'select') {
    //查询优惠卷
    var collar_data = await DB2.where({ login_openid: event.login_openid }).get();
    return  collar_data;
  } else if (event.usetype == 'collar') {
    // 领取优惠卷
    var collar_data1 = await DB1.doc(event.collar_id).get();
    var collar_data2 = await DB2.where({ collar_id: event.collar_id, login_openid: event.login_openid }).get();
    // 判断是否优惠券还有库存
    if (collar_data1.data.number > 0) {
      // 判断是否领取优惠卷
      if (collar_data2.data.length == 0) {
        let datas = await DB2.add({
          data: {
            collar_id: event.collar_id,  //优惠卷id
            collar_inf: event.collar_inf,   //优惠卷详情
            login_openid: event.login_openid,   //用户openid
            receive_time: event.receive_time,    //领取时间
            over_time:event.collar_inf.over_time
          }
        });
        let datas1 = await DB1.doc(event.collar_id).update({ data: { number: _.inc(-1) } });
        if (datas1.stats.updated == 1) {
          return { code: 200, text: '领取成功', data: datas1 };
        } else {
          return { code: 400, text: '领取失败' };
        }
      } else {
        return { code: 400, text: '你已领取优惠券请勿重新领取。' }
      }
    } else {
      return { code: 400, text: '优惠券已领完。', collar_data1 }
    }
  } else if (event.usetype == 'get_home_coupon') {
    //请求优惠卷列表
    let coupon_list = await DB1.where({ number: _.gt(0), show_address:'frist'}).get();
    //请求公告列表
    let notice_list = await cloud.database().collection('notice_list').get();
    return {coupon_list,notice_list}
  }


}